var sprites = new Object();

// Some variables
sprites.count = 1; // Note - must be greater than 0
sprites.loaded = 0;
sprites.loadedImg = 0;

sprites.load = function() {
    var spriteUrl = "sprites/_spriteList.json";
    
    $.getJSON(spriteUrl, function(data) {
        sprites.loadSprites(data.sprites)
        console.log('Loaded list of sprites');
    }).fail(function(value) {
        return game.ajaxError(value);
    }(spriteUrl));
};

sprites.loadSprites = function(spriteList) {
    sprites.count = spriteList.length;
    
    $.each(spriteList, function(index, value) {
        $.getJSON(value, function(data) {
            sprites[data.id] = data;
            sprites.loaded++;
            console.log('Loaded "' + value + '"');
        }).fail(function(value) {
            return game.ajaxError(value);
        }(value));
    });
}

sprites.loadImages = function() {
    $.each(sprites, function(index, value) {
        if (typeof value == 'object') {
            value.img = new Image();
            $(value.img)
                .attr('src', 'img/' + value.source + '?_=' + game.timestamp)
                .load(function(id) {
                    return function() {
                        sprites.loadedImg++;
                        var sourceFix = $(sprites[index].img).attr('src');
                        console.log('Loaded "' + sourceFix.substr(0, sourceFix.lastIndexOf('?')) + '"');
                    };
                }(index))
                .on('error', function(value) {
                    return game.ajaxError(value);
                }('img/' + value.source));
        }
    });
};